package com.onetech.adrewards.free.activities;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.fedorvlasov.lazylist.ImageLoader;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.dialogs.ExitAppDialog2;
import com.onetech.adrewards.free.dialogs.FeedbackDialog;
import com.onetech.adrewards.free.dialogs.GuideDialogFragment;
import com.onetech.adrewards.free.dialogs.LoginBonusDialog;
import com.onetech.adrewards.free.dialogs.ReviewAppSuccessDialog;
import com.onetech.adrewards.free.fragments.ExchangeFragmentNew;
import com.onetech.adrewards.free.fragments.FeedbackOptionFragment;
import com.onetech.adrewards.free.fragments.GetPointsFragmentNewApi;
import com.onetech.adrewards.free.fragments.InviteFriendsFragment;
import com.onetech.adrewards.free.fragments.ListNewsFragment;
import com.onetech.adrewards.free.fragments.NavigationDrawerFragment;
import com.onetech.adrewards.free.fragments.SocialShareFragment;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.models.UserModel;
import com.onetech.adrewards.free.objects.UserInfoDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.todddavies.components.progressbar.ProgressWheel;

public class BaseNewActivity extends ActionBarActivity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks, OnClickListener,
		OnPageChangeListener {
	private NavigationDrawerFragment mNavigationDrawerFragment;

	private CharSequence mTitle;
	private ActionBar mActionbar;

	private TextView mAppTitle = null;
	// private ImageView mHomeBanner = null;
	private ProgressBar mCoinProgressBar = null;
	private TextView mMyCoins = null;
	private TextView mMaxCoins = null;
	private View mQuestionBtn = null;

	private View mFooterView = null;
	private View mMyPointContainer = null;
	private View mContentProgressbarCoins = null;

	// private View mNotFoundData = null;
	// private View mWaitingForLoading = null;
	protected View mBtnRetry = null;
	protected ProgressWheel mProgress = null;

	protected int mUserCoins = 0;
	// public int currentView = R.id.menuMiddle;

	protected GetUserInfo mGetUserInfo = null;
	private ImageView mNaviMenu = null;
	public String reviewSuccessMessage = "";
	public boolean isReviewApp = false;

	public interface ExitHandler {
		public void doExit();
	}

	private ExitHandler mHandler = null;

	public static int indexTabGetPoint = 1;
	public static int indexTabMain = 1;

	private View menuBottomLeft = null;
	private View menuBottomMiddle = null;
	private View menuBottomRight = null;
	public int currentView = R.id.menuMiddle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.permitAll().build());
		}
		setContentView(R.layout.activity_home);

		mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mTitle = getTitle();

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));

		mActionbar = getSupportActionBar();
		mActionbar.hide();
		initView();
		initListener();
		
		if (AppConfig.LOGIN_BONUS) {
			 
			LoginBonusDialog mLoginBonusDialog = new LoginBonusDialog(
					BaseNewActivity.this);
			mLoginBonusDialog.show();
		}

		mHandler = new ExitHandler() {
			@Override
			public void doExit() {
				try {
					ImageLoader.getInstance(getApplicationContext())
							.clearMemCache();
				} catch (Exception e) {
				} finally {
					finish();
				}
			}
		};
		overridePendingTransition(R.anim.fragment_fade_in,
				R.anim.fragment_fade_out);

		getSupportFragmentManager().addOnBackStackChangedListener(
				new OnBackStackChangedListener() {

					@Override
					public void onBackStackChanged() {
						Fragment f = getSupportFragmentManager()
								.findFragmentById(R.id.container);
						if (f != null) {
							updateTitleAndDrawer(f);
						}

					}
				});
	}
	private void updateTitleAndDrawer (Fragment fragment){
		  String fragClassName = fragment.getClass().getName();
		 
		  if (fragClassName.equals(GetPointsFragmentNewApi.class.getName())){
			  setAppTittle(getString(R.string.app_name));
			  showFooterView(true);
			  currentView=R.id.menuMiddle;
			  switchLayout(currentView);
			  return;
		  }
		  if (fragClassName.equals(ExchangeFragmentNew.class.getName())){
			  setAppTittle(getString(R.string.app_name));
			  showFooterView(true);
			  currentView=R.id.menuRight;
			  switchLayout(currentView);
			  return;
		  }
		  if (fragClassName.equals(ListNewsFragment.class.getName())){
			  setAppTittle(getString(R.string.app_name));
			  showFooterView(true);
			  currentView=R.id.menuLeft;
			  switchLayout(currentView);
			  return;
		  }
		  if (fragClassName.equals(InviteFriendsFragment.class.getName())){
			  setAppTittle(getString(R.string.invite_friend_title));
			  showFooterView(false);
			  return;
		  }
		  if (fragClassName.equals(SocialShareFragment.class.getName())){
			  setAppTittle(getString(R.string.app_name));
			  showFooterView(false);
			  return;
		  }
		}
	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// update the main content by replacing fragments
		FragmentManager fragmentManager = getSupportFragmentManager();
		Fragment mFragment = fragmentManager.findFragmentById(R.id.container);
		String fragmentName = "";
		if (mFragment != null) {
			fragmentName = fragmentManager.findFragmentById(R.id.container)
					.getClass().getName();
			if (fragmentName.equals(GetPointsFragmentNewApi.class.getName())) {
				GetPointsFragmentNewApi fragment = (GetPointsFragmentNewApi) fragmentManager
						.findFragmentById(R.id.container);
				
				if (fragment != null && position < 5) {
					fragment.switchFragmentViewPager(position - 1);
					return;					
				}
			}
		}

		indexTabMain = position;

		Fragment mMainFragment = null;
		switch (position) {
		case 0:
		case 1:
		case 2:
		case 3:
		case 4:
			showFooterView(true);
			currentView = R.id.menuMiddle;
			switchLayout(currentView);
			indexTabGetPoint = position - 1;
			if (indexTabGetPoint < 0) {
				indexTabGetPoint = 0;
			}
			mMainFragment = GetPointsFragmentNewApi.instantiate(
					getApplicationContext(),
					GetPointsFragmentNewApi.class.getName());
			setAppTittle(getString(R.string.app_name));
			break;
		case 5:
			showFooterView(false);
			indexTabGetPoint = 0;
			mMainFragment = InviteFriendsFragment.instantiate(
					getApplicationContext(),
					InviteFriendsFragment.class.getName());
			setAppTittle(getString(R.string.invite_friend_title));
			break;
		case 6:
			showFooterView(false);
			indexTabGetPoint = 0;
			mMainFragment = SocialShareFragment.instantiate(
					getApplicationContext(),
					SocialShareFragment.class.getName());
			setAppTittle(getString(R.string.app_name));
			break;
		case 7:
			showFooterView(true);
			currentView = R.id.menuLeft;
			switchLayout(currentView);
			if (fragmentName.equals(ListNewsFragment.class.getName())) {
				return;
			}
			indexTabGetPoint = 0;
			mMainFragment = ListNewsFragment.instantiate(
					getApplicationContext(), ListNewsFragment.class.getName());
			break;
		case 8:
		case 9:
		case 10:
			showFooterView(true);
			currentView = R.id.menuRight;
			switchLayout(currentView);
			if (fragmentName.equals(ExchangeFragmentNew.class.getName())) {
				ExchangeFragmentNew mExchangeFragmentNew = (ExchangeFragmentNew) fragmentManager
						.findFragmentById(R.id.container);
				if (mExchangeFragmentNew != null) {
					switch (position) {
					case 8:
						mExchangeFragmentNew.menuSelected(1);
						break;
					case 9:
						mExchangeFragmentNew.menuSelected(3);
						break;
					case 10:
						mExchangeFragmentNew.menuSelected(2);
						break;
					default:
						mExchangeFragmentNew.menuSelected(1);
						break;
					}
				}
				return;
			}
			indexTabGetPoint = 0;
			mMainFragment = ExchangeFragmentNew.instantiate(
					getApplicationContext(),
					ExchangeFragmentNew.class.getName());

			break;
		case 11:
			showFooterView(false);
			indexTabGetPoint = 0;
			mMainFragment = FeedbackOptionFragment.instantiate(
					getApplicationContext(),
					FeedbackOptionFragment.class.getName());
			setAppTittle(getString(R.string.feedback_title));
			break;

		default:
			showFooterView(true);
			indexTabGetPoint = 0;
			mMainFragment = GetPointsFragmentNewApi.instantiate(
					getApplicationContext(),
					GetPointsFragmentNewApi.class.getName());
			setAppTittle(getString(R.string.app_name));
			break;
		}
		// FragmentTransaction mFragmentTransaction =
		// fragmentManager.beginTransaction();
		// mFragmentTransaction.setCustomAnimations(R.anim.fragment_fade_in,
		// R.anim.fragment_fade_out);
		//
		// mFragmentTransaction.replace(R.id.container, mMainFragment)
		// .commit();
		replaceFragment(mMainFragment);
	}

	public void onSectionAttached(int number) {
		switch (number) {
		case 1:
			mTitle = getString(R.string.title_section1);
			break;
		case 2:
			mTitle = getString(R.string.title_section2);
			break;
		case 3:
			mTitle = getString(R.string.title_section3);
			break;
		}
	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}

	// Base functions
	private void initView() {
		menuBottomLeft = (LinearLayout) findViewById(R.id.menuLeft);
		menuBottomMiddle = (LinearLayout) findViewById(R.id.menuMiddle);
		menuBottomRight = (LinearLayout) findViewById(R.id.menuRight);

		mNaviMenu = (ImageView) findViewById(R.id.naviMenuIcon);
		mNaviMenu.setVisibility(View.VISIBLE);
		mFooterView = (LinearLayout) this.findViewById(R.id.mainAppFooter);

		// mHomeBanner = (ImageView) this.findViewById(R.id.homeBanner);
		mCoinProgressBar = (ProgressBar) this
				.findViewById(R.id.myProgressBarPoint);
		mCoinProgressBar.setMax(AppConfig.MIN_COIN_EXCHANGE);
		mMyPointContainer = (LinearLayout) this.findViewById(R.id.myPoints);
		mContentProgressbarCoins = (LinearLayout) this
				.findViewById(R.id.myContentProgressBarCoins);

		mAppTitle = (TextView) findViewById(R.id.appTitle);
		mMyCoins = (TextView) findViewById(R.id.myCoins);
		mMaxCoins = (TextView) findViewById(R.id.maxCoins);
		mQuestionBtn = (LinearLayout) findViewById(R.id.appQuestion);

		//initNotFoundAndLoadingView();
	}

//	private void setDefaultMenuBackground() {
//		menuBottomLeft
//				.setBackgroundResource(R.drawable.menu_bottom_background_selected);
//		menuBottomMiddle
//				.setBackgroundResource(R.drawable.menu_bottom_background_normal);
//		menuBottomRight
//				.setBackgroundResource(R.drawable.menu_bottom_background_normal);
//	}

	public void switchLayout(int id) {
		if (menuBottomLeft == null || menuBottomMiddle == null
				|| menuBottomRight == null) {
			return;
		}
		switch (id) {
		case R.id.menuLeft:
			menuBottomLeft
					.setBackgroundResource(R.drawable.menu_bottom_background_selected);
			menuBottomMiddle
					.setBackgroundResource(R.drawable.menu_bottom_background_normal);
			menuBottomRight
					.setBackgroundResource(R.drawable.menu_bottom_background_normal);
			break;
		case R.id.menuMiddle:
			menuBottomLeft
					.setBackgroundResource(R.drawable.menu_bottom_background_normal);
			menuBottomMiddle
					.setBackgroundResource(R.drawable.menu_bottom_background_selected);
			menuBottomRight
					.setBackgroundResource(R.drawable.menu_bottom_background_normal);
			break;
		case R.id.menuRight:
			menuBottomLeft
					.setBackgroundResource(R.drawable.menu_bottom_background_normal);
			menuBottomMiddle
					.setBackgroundResource(R.drawable.menu_bottom_background_normal);
			menuBottomRight
					.setBackgroundResource(R.drawable.menu_bottom_background_selected);
			break;
		default:
			break;
		}
	}

	public void setAppTittle(String title) {
		if (mAppTitle != null) {
			mAppTitle.setText(title);
		}
	}

	private void initListener() {
		// mHomeBanner.setOnClickListener(this);
		mContentProgressbarCoins.setOnClickListener(this);
		mQuestionBtn.setOnClickListener(this);
		mNaviMenu.setOnClickListener(this);

		menuBottomLeft.setOnClickListener(this);
		menuBottomMiddle.setOnClickListener(this);
		menuBottomRight.setOnClickListener(this);
		// mBtnRetry.setOnClickListener(this);
	}

	protected void showFooterView(boolean isShow) {
		if (mFooterView != null) {
			mFooterView.setVisibility(isShow ? View.VISIBLE : View.GONE);
		}
	}

	protected void showMyPoints(boolean isShow) {
		mMyPointContainer.setVisibility(isShow ? View.VISIBLE : View.GONE);
	}

	protected void updateCoins(String myCoins, String maxCoins) {
		try {
			mMyCoins.setText(myCoins);
			mMaxCoins.setText(maxCoins);
			mCoinProgressBar.setProgress(Integer.valueOf(myCoins));
		} catch (Exception e) {
			return;
		}
	}

	public void showFeedbackDialog() {
		FeedbackDialog mFeedbackDialog = new FeedbackDialog(this);
		mFeedbackDialog.show();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.appQuestion:
			new GuideDialogFragment().show(getSupportFragmentManager(), "");
			break;
		case R.id.homeBanner:
			LoginBonusDialog mLoginBonusDialog = new LoginBonusDialog(this);
			mLoginBonusDialog.show();
			break;
		case R.id.myContentProgressBarCoins:
			// Intent intent = new Intent(this, PointHistoryActivity.class);
			// startActivity(intent);
			onNavigationDrawerItemSelected(9);
			return;
		case R.id.naviMenuIcon:
			mNavigationDrawerFragment.openNaviDrawer();
			break;
		case R.id.menuLeft:
			currentView = R.id.menuLeft;
			onNavigationDrawerItemSelected(7);
			break;
		case R.id.menuMiddle:
			currentView = R.id.menuMiddle;
			onNavigationDrawerItemSelected(1);
			break;
		case R.id.menuRight:
			currentView = R.id.menuRight;
			onNavigationDrawerItemSelected(8);
			break;
		default:
			break;
		}
		switchLayout(currentView);
		// switchCurrentItemByViewId(currentView);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int arg0) {

	}

	@Override
	public void onResume() {
		super.onResume();
		getUIDFromStore();
		getUserCoinsFromStore();
		checkReviewApp();
		catchSchemaUrl();
		getUserInfo();
	
	}

	private void catchSchemaUrl() {
		try {
			Uri uri = getIntent().getData();
			if (uri != null) {
				String oauth_token = uri
						.getQueryParameter(SocialShareFragment.IEXTRA_OAUTH_TOKEN);
				String oauth_verifier = uri
						.getQueryParameter(SocialShareFragment.IEXTRA_OAUTH_VERIFIER);

				if (oauth_token != null && oauth_token.trim().length() > 0
						&& oauth_verifier != null
						&& oauth_verifier.trim().length() > 0) {
					onNavigationDrawerItemSelected(6);
				}
			}
		} catch (Exception e) {
			return;
		}
	}

	private void checkReviewApp() {
		if (isReviewApp) {
			isReviewApp = false;

			AdrewadsUtils.setStore(getApplicationContext(),
					Cache.REVIEW_APP_KEY, "Done");
			if (reviewSuccessMessage != null
					&& reviewSuccessMessage.trim().length() > 0) {
				ReviewAppSuccessDialog dialog = new ReviewAppSuccessDialog(
						BaseNewActivity.this, getString(R.string.app_name),
						reviewSuccessMessage);
				dialog.show();
			}
		}
	}

	public int getUserCoins() {
		return mUserCoins;
	}

	protected void getUIDFromStore() {
		AdrewadsUtils.checkUId();
	}

	protected void getUserCoinsFromStore() {
		try {
			String coins = CommonModel.getInstance().getStore(
					Cache.ONE_TECH_USER_POINTS);
			if (coins != null) {
				mUserCoins = Integer.valueOf(coins);
			}
		} catch (Exception e) {
		}
	}

	public void getUserInfo() {
		if (mGetUserInfo == null || mGetUserInfo.getStatus() == Status.FINISHED) {
			mGetUserInfo = new GetUserInfo();
			mGetUserInfo.execute();
		}
	}

	private class GetUserInfo extends AsyncTask<Void, Void, UserInfoDTO> {
		@Override
		protected UserInfoDTO doInBackground(Void... params) {
			return UserModel.getInstance().getUserInfo(AppConfig.uId);
		}

		@Override
		protected void onPostExecute(UserInfoDTO result) {
			super.onPostExecute(result);

			try {
				if (result != null
						&& result.getTotal_coin().trim().length() > 0) {
					// AppConfig.userCoins=Integer.valueOf(result.getTotal_coin().trim());
					mUserCoins = Integer.valueOf(result.getTotal_coin().trim());

					updateCoins(result.getTotal_coin(),
							String.valueOf(AppConfig.MIN_COIN_EXCHANGE));
					// mCoinProgressBar.setProgress(Integer.valueOf(result.getTotal_coin()));
				}
			} catch (Exception e) {
				return;
			}
		}
	}

	// @Override
	// public void onBackPressed() {
	// // super.onBackPressed();
	// try {
	// ExitAppDialog2 mExitAppDialog = new ExitAppDialog2(this, mHandler);
	// mExitAppDialog.show();
	// } catch (Exception e) {
	// return;
	// }
	// }
	@Override
	public void onBackPressed() {
		if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
			try {
				ExitAppDialog2 mExitAppDialog = new ExitAppDialog2(this,
						mHandler);
				mExitAppDialog.show();
			} catch (Exception e) {
				return;
			}
		} else {
			super.onBackPressed();
		}
	}

	private void replaceFragment(Fragment fragment) {
		String backStateName = fragment.getClass().getName();
		String fragmentTag = backStateName;

		FragmentManager fragmentManager = getSupportFragmentManager();
		boolean fragmentPopped = fragmentManager.popBackStackImmediate(
				backStateName, 0);

		if (!fragmentPopped
				&& fragmentManager.findFragmentByTag(fragmentTag) == null) { // fragment
																				// not
																				// in
																				// back
																				// stack,
																				// create
																				// it.

			// FragmentTransaction mFragmentTransaction =
			// fragmentManager.beginTransaction();
			// mFragmentTransaction.setCustomAnimations(R.anim.fragment_fade_in,
			// R.anim.fragment_fade_out);
			//
			// mFragmentTransaction.replace(R.id.container, mMainFragment)
			// .commit();

			FragmentTransaction ft = fragmentManager.beginTransaction();
			ft.replace(R.id.container, fragment, fragmentTag);
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//			if(backStateName==GetPointsFragmentNewApi.class.getName()|| backStateName==ListNewsFragment.class.getName()|| backStateName==ExchangeFragmentNew.class.getName()){
//				ft.addToBackStack(backStateName);
//			}else{
//				ft.addToBackStack(null);
//			}
			ft.addToBackStack(backStateName);
			ft.commit();
		}
	}

	public void showToast(String text) {
		Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
	}

//	protected void initNotFoundAndLoadingView() {
//		// mNotFoundData=(LinearLayout)
//		// findViewById(R.id.notFoundDataContainer);
//		// mWaitingForLoading=(LinearLayout) findViewById(R.id.waitingLoading);
//		// mProgress=(ProgressWheel)findViewById(R.id.progressWheel);
//		// mProgress.spin();
//		// showNotFoundOrLoadingView(false, true);
//		// mBtnRetry=(LinearLayout)findViewById(R.id.btnRetry);
//
//	}
//
//	public void showNotFoundOrLoadingView(boolean isShowNotFound,
//			boolean isShowLoading) {
//		// if(isShowNotFound){
//		// mNotFoundData.setVisibility(View.VISIBLE);
//		// }else{
//		// mNotFoundData.setVisibility(View.GONE);
//		// }
//		// if(isShowLoading){
//		// mProgress.spin();
//		// mWaitingForLoading.setVisibility(View.VISIBLE);
//		// }else{
//		// mWaitingForLoading.setVisibility(View.GONE);
//		// mProgress.stopSpinning();
//		// }
//	}
	// end base functions

}
